package com.cavy.platform.server.validator;

import com.cavy.platform.server.BeansProvider;
import com.cavy.platform.server.dto.PluginRepositorySettingCreateDto;
import com.cavy.platform.server.repository.PluginRepositorySettingRepository;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 验证插件仓库名称不能重复
 */
public class NotRepeatPluginRepositoryNameValidator implements ConstraintValidator<NotRepeatPluginRepositoryName, PluginRepositorySettingCreateDto> {

    private PluginRepositorySettingRepository bean;

    @Override
    public void initialize(NotRepeatPluginRepositoryName notRepeatPluginName) {
        bean = BeansProvider.getBean(PluginRepositorySettingRepository.class);
    }

    @Override
    public boolean isValid(PluginRepositorySettingCreateDto dto, ConstraintValidatorContext context) {
        assert bean != null;
        long count = bean.countByName(dto.getName());
        if (count > 0) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("已经存在该名称的仓库").addPropertyNode("name").addConstraintViolation();
            return false;
        }

        long codeCount = bean.countByCode(dto.getCode());
        if (codeCount > 0) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("已经存在该code的仓库").addPropertyNode("code").addConstraintViolation();
            return false;
        }

        return true;
    }
}
